<template>
	<view class="baseForm">
		<view class="overhidden">
			<view>
				<!-- 条码录入 -->
				<!-- <view class="searchScan_div">
					<scan-bar
						ref="scanBarRef"
						placeholder="请扫描或输入模具编号"
						@code-scanned="getScanResult"
						:key="datekey"></scan-bar>
				</view> -->
				<view class="upload-scan">
					<u-search
						v-model="formData.consumeCode"
						shape="round"
						bgColor="#fff"
						:show-action="true"
						actionText="搜索"
						:animation="true"
						class="search"
						@search="searchList"
						@clear="searchList"
						@custom="searchList"
					></u-search>
					<u-icon name="scan" size="27px" :bold="false" @click="scanHandle"></u-icon>
				</view>
				<u--form labelPosition="top" :model="formData" :rules="rules" labelWidth="300" ref="uForm" class="form" errorType="toast">
					<view v-show="!taskInfo?.code && loading === false" class="flex justify-center font-14" style="margin: 30px 0 30px 0">暂无模具信息，请录入模具编号</view>
					<u-loading-icon class="flex justify-center mt-20" textSize="18" v-show="loading"></u-loading-icon>
					<!-- 尺寸信息 -->
					<!-- <view v-if="taskInfo?.code" style="margin: 3px 13px -10px">
						<view class="flex flex-col justify-between flex-1 h-full">
							<view class="record-content">
								<view class="record-item" style="padding: 0 2px;">
									<text style="font-size: 14px;">{{taskInfo?.code}}</text>
									<text style="font-size: 14px;">{{!taskInfo?.eamAssetInfo?'待入库':'已入库'}}</text>
								</view>
							</view>
						</view>
					</view> -->
					<!-- 模具详情 -->
					<ConsumablesDetachInfo v-if="taskInfo.code" :taskInfo="taskInfo"></ConsumablesDetachInfo>

					<view class="plan card record-content" style="margin-bottom: 70px" v-if="taskInfo?.code">
						<view
							v-show="!taskInfo?.eamSopStandardDTO?.itemDTOS || taskInfo?.eamSopStandardDTO?.itemDTOS.length === 0"
							class="flex justify-start grey-color"
							style="margin: 12px 0 10px"
						>
							暂无尺寸点检信息
						</view>
						<view class="overhidden" v-for="(item, index) in taskInfo?.eamSopStandardDTO?.itemDTOS" :key="index">
							<view>
								<view class="record-content">
									<!-- <view class="record-item">
										<text>{{ item?.sizeName || '' }}</text>
										<text v-if="item?.standardMinValue !== item?.standardMaxValue">上下线值：{{ item?.standardMinValue || '' }}-{{ item?.standardMaxValue || '' }}</text>
										<text v-else>上下线值：{{ item?.standardMinValue || '' }}</text>
									</view> -->
									<!-- 两种样式，可以任意切换 -->
									<view class="record-item">
										<!-- <text>尺寸名称</text> -->
										<view class="title_new">
											{{ item?.sopItemName || '' }}
											<u-icon
												v-if="item?.sopItemMethod"
												name="info-circle-fill"
												color="rgb(192, 196, 204)"
												size="18"
												@click="openInfoModal(item.sopItemMethod)"
											></u-icon>
										</view>
									</view>
									<view class="record-item" v-if="item.standardValue == 1 && !(!item.standardMinValue && !item.standardMaxValue)">
										<text>上下限值</text>
										<text v-if="item?.standardMinValue !== item?.standardMaxValue">
											{{ item?.standardMinValue || '' }}-{{ item?.standardMaxValue || '' }}{{ item?.standardValueUnit || '' }}
										</text>
										<text v-else>{{ item?.standardMinValue || '' }}{{ item?.standardValueUnit || '' }}</text>
									</view>
									<view class="record-item" v-if="item.standardValue == 1">
										<view class="flex">
											实际值
											<text class="require_icon" v-if="item?.sopExecute == '1'">*</text>
										</view>
										<u--input
											v-model="item.saveValue"
											placeholder="请输入"
											class="minInput"
											:class="sizeColorHandle(item.saveValue, item?.standardMinValue, item?.standardMaxValue)"
											inputAlign="right"
											clearable
											border="none"
										></u--input>
									</view>
									<view class="record-item" v-if="item.standardValue == 2">
										<view class="flex">
											实际值
											<text class="require_icon" v-if="item?.sopExecute == '1'">*</text>
										</view>
										<view @click="hideKeyboard(index, item.details ?? [])" class="flex input-box">
											<u--input
												v-model="item.saveValueName"
												border="none"
												placeholder="请选择"
												readonly
												class="minInput"
												:class="sizeColorHandle1(item.saveValue, item.details ?? [])"
											></u--input>
											<image @click.stop="clearData(index)" v-show="item.saveValue" src="@/static/image/delete.png" class="deleteIcon" />
										</view>
									</view>
								</view>
								<!-- 待需要上传图片后启用 -->
								<view class="mt-8 flex" v-if="item.sopImage == '1'">
									<upload-image
										:multiple="false"
										:key="index"
										:keys="index"
										@fileChange="(list) => getImages(list, index)"
										:list="item.images ?? []"
										:capture="capture"
									></upload-image>
								</view>
							</view>
							<u-divider v-show="index + 1 !== taskInfo?.eamSopStandardDTO.itemDTOS.length"></u-divider>
						</view>

						<!-- 查看页面并且没有现场图片则不展示 -->
						<!-- <view>
							<view class="title flex justify-between">
								<text class="mt-4">现场图片</text>
							</view>

							<view class="mt-8">
								<view class="mt-8 flex">
									<upload-image :multiple="false" :keys="4545" @fileChange="getSceneImages" :list="taskInfo.images ?? []" :capture="capture"></upload-image>
								</view>
							</view>
						</view> -->
					</view>
					<view style="height: 50px"></view>
					<!-- 提交 -->
					<view class="submit_btn_divTwo" style="margin-bottom: 50px">
						<button type="default" class="grey_btnTwo" @click="resetFields">重 置</button>
						<button type="primary" :disabled="postLoading" :loading="postLoading" @click="submit" class="submit_btnTwo">保 存</button>
					</view>
					<view class="submit_btn_divTwo">
						<button type="default" class="grey_btnTwo" @click="scrapBtn">报 废</button>
						<button type="primary" :disabled="postLoading" :loading="postLoading" @click="normalBtn" class="submit_btnTwo">正 常</button>
					</view>
				</u--form>
			</view>
		</view>
		<!-- 实际值选择picker -->
		<u-picker :show="showPicker" :columns="currentColumns" keyName="text" immediateChange @cancel="showPicker = false" @confirm="changeData"></u-picker>
		<u-modal :show="showInfo" :content="contentInfo" @confirm="showInfo = false"></u-modal>
	</view>
</template>

<script lang="ts" setup>
import { ref, reactive, toRaw } from 'vue';
import { http } from '@/utils/http';
import { mockData } from './index';
import { onPageScroll, onShow, onLoad } from '@dcloudio/uni-app';
import UploadImage from '@/components/upload-image-ssr.vue';
import ScanBar from '@/components/scan-bar/index.vue';
import ConsumablesDetachInfo from '@/pages/eam/mold/enterWarehouse/components/info.vue';
import { sizeColorHandle1, sizeColorHandle } from '@/utils/common';
import { toScanCode } from '@/components/hs-scancode/scan.js';

// 刚进来 页面置顶
onLoad(() => {
	uni.pageScrollTo({
		scrollTop: 0,
		duration: 0
	});
});

// 作业方法提示框
const showInfo = ref(false);
const contentInfo = ref('');
function openInfoModal(data) {
	showInfo.value = true;
	contentInfo.value = `作业方法：${data}`;
}

/**
 * 选择实际值
 */
const showPicker = ref(false);
const currentColumns = reactive([[]]);
const currentIndex = ref();

/**
 * 组织键盘弹出
 */
function hideKeyboard(index, list) {
	const lists = JSON.parse(JSON.stringify(list));
	lists.forEach((item) => {
		item.text = `${item.standardValue} - ${item.resultValue == '1' ? '正常' : '异常'}`;
	});
	currentIndex.value = index;
	currentColumns[0] = lists ?? [];
	showPicker.value = true;
	uni.hideKeyboard();
}
function clearData(index) {
	taskInfo.value.eamSopStandardDTO.itemDTOS[index].saveValue = '';
	taskInfo.value.eamSopStandardDTO.itemDTOS[index].saveValueName = '';
	showPicker.value = false;
}
function changeData(e) {
	taskInfo.value.eamSopStandardDTO.itemDTOS[currentIndex.value].saveValueName = e.value[0].standardValue;
	taskInfo.value.eamSopStandardDTO.itemDTOS[currentIndex.value].saveValue = e.value[0].id;
	showPicker.value = false;
}

// 表单详情
let formData = reactive({
	consumeCode: ''
});

// 初始化页面，获取检查详情
let taskInfo = ref<any>({});
const loading = ref(false);

// 表单规则定义
const rules = ref({});

// 摄像头参数设置
const capture = ref(['camera', 'album']);
// 获取图片
function getImages(list, index) {
	const current = JSON.parse(JSON.stringify(taskInfo.value.eamSopStandardDTO.itemDTOS))[index];
	current.images = [];
	list?.forEach((item) => {
		current.images.push(item);
	});
	const elder = JSON.parse(JSON.stringify(taskInfo.value.eamSopStandardDTO.itemDTOS));
	elder[index] = current;
	taskInfo.value.eamSopStandardDTO.itemDTOS = elder;
}

// 获取现场图片
function getSceneImages(list) {
	taskInfo.value.images = list;
}

// 获取扫码结果
function getScanResult(result: any) {
	formData.consumeCode = result;
	resetData();
	if (result) {
		getDeviceInfo(result);
	}
}

// form信息重置
function resetData() {
	taskInfo.value = {};
	formData.consumeCode = '';
	uni.pageScrollTo({
		scrollTop: 0,
		duration: 100
	});
}

// 点击扫码

function scanHandle() {
	toScanCode({
		onlyFromCamera: true // 只允许通过相机扫码
	})
		.then((res) => {
			uni.showToast({
				icon: 'success',
				title: '扫码成功'
			});
			resetData();
			formData.consumeCode = res;

			if (res) {
				getDeviceInfo(res);
			}
		})
		.catch((e) => {
			uni.showToast({
				icon: 'error',
				title: e
			});
		});
}

const searchList = () => {
	if (formData.consumeCode) {
		getDeviceInfo(formData.consumeCode);
	} else {
		resetData();
	}
};

// 重置表单信息 & 光标自动blur
const scanBarRef = ref();
const datekey = ref(new Date());
function resetFields() {
	resetData();
	scanBarRef.value.reset();
	datekey.value = new Date();
}

// 校验提交
const uForm = ref();
const postLoading = ref(false);
async function submit() {
	console.log(taskInfo.value);
	// 校验是否录入模具编号成功
	if (!taskInfo.value.code) {
		uni.showToast({
			title: '请录入模具编号',
			icon: 'none'
		});
		return false;
	}
	// 校验是否为数字
	const info = taskInfo.value?.eamSopStandardDTO?.itemDTOS || [];
	for (let i = 0; i < info.length; i++) {
		if (info[i].standardValue == '1') {
			if (isNaN(Number(info[i].saveValue))) {
				uni.showToast({
					title: `${info[i].sopItemName}的实际值只能为数字`,
					icon: 'none'
				});
				return false;
			}
		}
	}
	// 校验必填项是否填写
	const infos = taskInfo.value?.eamSopStandardDTO?.itemDTOS ?? [];
	if (infos.length) {
		for (let i = 0; i < infos.length; i++) {
			if (infos[i].sopExecute == '1' && !infos[i].saveValue) {
				uni.showToast({
					title: `${infos[i].sopItemName}的实际值不能为空`,
					icon: 'none'
				});
				return false;
			}
		}
	}
	// save提交
	postLoading.value = true;
	const result: any = await http({
		method: 'POST',
		url: `/eam/eammodmanage/save`,
		data: toRaw(taskInfo.value)
	}).catch(() => {
		postLoading.value = false;
	});
	if (result?.code == 200) {
		uni.showToast({
			title: !taskInfo.value.eamAssetInfo ? '入库成功' : '提交成功'
		});
		setTimeout(() => {
			postLoading.value = false;
			resetFields();
		}, 500);
	}
}

// 获取模具信息（接口请求）
async function getDeviceInfo(consumeCode: string) {
	taskInfo.value = JSON.parse(JSON.stringify(mockData));
	loading.value = true;
	const data: any = await http({
		method: 'GET',
		url: `/eam/eammodmanage/getMdmmaterial/${consumeCode}`,
		data: {}
	}).catch(() => {
		loading.value = false;
		// resetFields();
	});
	if (data?.data) {
		// taskInfo.value = data?.data;
		taskInfo.value = JSON.parse(JSON.stringify(mockData));
	}
	loading.value = false;
	// 模拟数据返回，调试使用（保留）
	// setTimeout(() => {
	// 	loading.value = false;
	// 	taskInfo.value = JSON.parse(JSON.stringify(mockData));
	// }, 500);
}

// 报废
const scrapBtn = (): void => {};
// 正常
const normalBtn = (): void => {};
</script>

<style lang="scss" scoped>
@import '@/static/css/standard_item.scss';
.upload-scan {
	padding: $uni-page-padding;
	padding-top: 5px;
	padding-bottom: 1px;
	display: flex;
	align-items: center;
	// box-shadow: 0 1px 10px 0px rgb(19 10 236 / 10%);
	.u-icon {
		margin-left: 8px;
	}
}

.submit_btnTwo {
	margin: 0px 20rpx 20rpx 10rpx;
}
.grey_btnTwo {
	margin: 0px 10rpx 20rpx 20rpx;
	height: 45px;
	line-height: 45px;
	border: 1px solid #ccc;
}

.submit_btn_divTwo {
	position: fixed;
	display: flex;
	align-items: center;
	width: 100%;
	bottom: 0;
	z-index: 10;
	uni-button {
		flex: 1;
		border-radius: 10px;
	}
}
</style>
